<script lang="ts" setup>
import { accountLogin } from '@/api/UserAccountApi.ts'
import { AccountLoginEvent } from '@/config/event/AccountLoginEvent.ts'
import { useAccountStore } from '@/config/store/UseAccountStore.ts'
import { type ArcoForm, type ArcoFormRules, ArcoFormTool } from '@/tool/ArcoFormTool.ts'
import { ref } from 'vue'
import { useRouter } from 'vue-router'

const isLoading = ref(false)
const formRef = ref<ArcoForm | null>(null)
const formData = ref({
    username: '',
    password: '',
})
const formRule: ArcoFormRules = {
    username: [ { required: true, type: 'string', maxLength: 128, message: '不能为空' } ],
    password: [ { required: true, type: 'string', maxLength: 128, message: '不能为空' } ],
}

const hidePassword = ref(true)
const loginAccount = useAccountStore()
const router = useRouter()

const onFormSubmit = () => {
    isLoading.value = true
    ArcoFormTool.validate(formRef)
            .then(() => accountLogin(formData.value))
            .then(res => {
                loginAccount.onLogin(res)
                document.dispatchEvent(new AccountLoginEvent())
                router.push('/')
            })
            .finally(() => isLoading.value = false)
}

</script>

<template>
<div class="login-page" role="main">

    <a-card>
        <a-spin :loading="isLoading">
            <a-form
                    ref="formRef"
                    :model="formData"
                    :rules="formRule"
                    auto-label-width
                    layout=""
                    @submit="onFormSubmit"
            >

                <a-form-item field="username" hide-asterisk>
                    <a-input v-model="formData.username" autocomplete="username" placeholder="用户名" />
                </a-form-item>

                <a-form-item field="password" hide-asterisk>
                    <a-input-password
                            v-model="formData.password"
                            v-model:visibility="hidePassword"
                            :defaultVisibility="hidePassword"
                            allow-clear
                            autocomplete="password"
                            placeholder="请输入密码"
                    />
                </a-form-item>

                <a-form-item>
                    <a-button :loading="isLoading" class="login-button" html-type="submit">
                        登 录
                    </a-button>
                </a-form-item>

            </a-form>
        </a-spin>
    </a-card>
</div>

</template>

<style lang="scss" scoped>
.login-page {
    height: 100vh;

    display: flex;
    justify-content: center;
    align-items: center;

    .arco-card {
        width: 500px;
        padding: 100px 20px 50px;
        background-color: rgba(255, 255, 255, .5);
    }

    :deep(.arco-spin) {
        display: block;
    }

    .login-button {
        width: 100%;
    }

}
</style>
